package spring.framework.context.support;

import cn.hutool.core.bean.BeanException;
import spring.framework.beans.BeansException;
import spring.framework.beans.factory.ConfigurableListableBeanFactory;
import spring.framework.beans.factory.config.BeanFactoryPostProcessor;
import spring.framework.beans.factory.config.BeanPostProcessor;
import spring.framework.context.ConfigurableApplicationContext;
import spring.framework.core.io.DefaultResourceLoader;

import java.util.Map;

/**
 * @author fun.pengzh
 * @class spring.framework.context.support.AbstractApplicationContext
 * @desc
 * @since 2021-09-30
 */
public abstract class AbstractApplicationContext extends DefaultResourceLoader implements ConfigurableApplicationContext {

    @Override
    public void refresh() throws BeansException {

        //1、创建BeanFactory并加载BeanDefinition
        refreshBeanFactory();

        //2、获取BeanFactory
        ConfigurableListableBeanFactory beanFactory = getBeanFactory();

        //3、在Bean实例化之前，执行BeanFactoryPostprocess
        invokeBeanFactoryPostProcessors(beanFactory);

        //4、BeanPostProcessor需要提前其他Bean之前注册
        registerBeanPostProcessors(beanFactory);

        //5、提前实例化单例Bean对象
        beanFactory.preInstantiateSingletons();

    }

    protected abstract void refreshBeanFactory() throws BeansException;

    protected abstract ConfigurableListableBeanFactory getBeanFactory();

    private void invokeBeanFactoryPostProcessors(ConfigurableListableBeanFactory beanFactory) {
        Map<String, BeanFactoryPostProcessor> beansOfTypes = beanFactory.getBeansOfTypes(BeanFactoryPostProcessor.class);
        for (BeanFactoryPostProcessor beanFactoryPostProcessor : beansOfTypes.values()) {
            beanFactoryPostProcessor.postProcessBeanFactory(beanFactory);
        }
    }

    private void registerBeanPostProcessors(ConfigurableListableBeanFactory beanFactory) {
        Map<String, BeanPostProcessor> beansOfTypes = beanFactory.getBeansOfTypes(BeanPostProcessor.class);
        for (BeanPostProcessor beanPostProcessor : beansOfTypes.values()) {
            beanFactory.addBeanPostProcessor(beanPostProcessor);
        }
    }

    @Override
    public <T> Map<String, T> getBeansOfTypes(Class<T> type) throws BeansException {
        return getBeanFactory().getBeansOfTypes(type);
    }

    @Override
    public String[] getBeanDefinitionNames() {
        return getBeanFactory().getBeanDefinitionNames();
    }

    @Override
    public Object getBean(String beaName, Object... args) throws BeansException {
        return getBeanFactory().getBean(beaName, args);
    }

    @Override
    public Object getBean(String beanName) throws BeanException {
        return getBeanFactory().getBean(beanName);
    }

    @Override
    public <T> T getBean(String beanName, Class<T> requireType) throws BeansException {
        return (T) getBeanFactory().getBean(beanName);
    }
}
